/**
 * 基础菜单 商品管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="searchGoods.goodsName"
          placeholder="输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column sortable prop="name" label="商品名称" width="200">
      </el-table-column>
      <el-table-column
        sortable
        prop="categoryName"
        label="所属类目"
        width="100"
      >
      </el-table-column>
      <el-table-column sortable prop="isOnSale" label="是否在售" width="100">
      </el-table-column>
      <el-table-column sortable prop="sortOrder" label="商品排序" width="100">
      </el-table-column>
      <el-table-column sortable prop="picUrl" label="商品主图" width="150">
        <template slot-scope="scope">
          <img :src="scope.row.picUrl" style="height: 50px; width: 100px" />
        </template>
      </el-table-column>
      <el-table-column sortable prop="isShow" label="商品展示" width="100">
      </el-table-column>
      <el-table-column sortable prop="isHot" label="是否上热门" width="120">
      </el-table-column>
      <el-table-column sortable prop="price" label="价格" width="100">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="60%"
      @click="closeDialog"
    >
      <el-form label-width="90px" :model="editForm" ref="editForm">
        <el-form-item label="商品名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属类目" prop="categoryId">
          <!-- <el-input size="small" v-model="editForm.deptNo" auto-complete="off" placeholder="请输入类目名称"></el-input> -->
          <el-select v-model="editForm.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在售" prop="isOnSale">
          <!-- <el-input size="small" v-model="editForm.deptNo" auto-complete="off" placeholder="请输入类目名称"></el-input> -->
          <el-radio-group v-model="editForm.isOnSale">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品排序" prop="sortOrder">
          <el-input
            size="small"
            v-model="editForm.sortOrder"
            auto-complete="off"
            placeholder="请输入商品排序，默认50"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品主图" prop="picUrl">
          <el-upload
            action="qiniuDomain"
            list-type="picture-card"
            :http-request="upLoadToQiniu"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="editForm.picUrl" :src="editForm.picUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <!-- <el-input
            size="small"
            v-model="editForm.picUrl"
            auto-complete="off"
            placeholder="请输入类目名称"
          ></el-input> -->
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="editForm.isShow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上热门" prop="isHot">
          <el-radio-group v-model="editForm.isHot">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <el-input
            type="textarea"
            autosize
            size="small"
            v-model="editForm.detail"
            auto-complete="off"
            placeholder="请输入商品详情"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
            size="small"
            v-model="editForm.price"
            auto-complete="off"
            placeholder="请输入类目名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="sku规格">
          <!-- <el-input size="small" v-model="editForm.deptNo" auto-complete="off" placeholder="请输入sku规格"></el-input> -->
          <el-button size="small" type="primary" @click="addSkuDialog"
            >添加</el-button
          >
          <el-table
            size="small"
            :data="editForm.goodsProductVo"
            highlight-current-row
            border
          >
            <el-table-column prop="picUrl" label="规格图" width="204">
              <template slot-scope="scope">
                <img
                  :src="scope.row.picUrl"
                  style="height: 50px; width: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格" width="204">
            </el-table-column>
            <el-table-column prop="price" label="规格价格" width="204">
            </el-table-column>
            <el-table-column label="操作" width="168" class="editAttr">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="updateSkuDialog(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteSku(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品参数">
          <el-button size="small" type="primary" @click="addAttributeDialog"
            >添加</el-button
          >
          <el-table
            size="small"
            :data="editForm.goodsAttributeVo"
            highlight-current-row
            border
          >
            <el-table-column prop="attribute" label="规格" width="260">
            </el-table-column>
            <el-table-column prop="value" label="值" width="260">
            </el-table-column>
            <el-table-column label="操作" width="260" class="editAttr">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteAttribute(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 添加sku界面 -->
    <!-- <GoodsSku
      :editSkuVisible.sync="editSkuVisible"
      :skuSpecifications="editForm.skuSpecifications"
      :editSku="editSku"
      @addSku="addSku"
      @updateSku="updateSku"
    >
    </GoodsSku> -->
    <el-dialog title="sku规格" :visible.sync="editSkuVisible" width="60%" @click="closeSkuDialog">
      <el-form label-width="90px"   ref="editSku">
         <el-form-item label="规格"  v-if="editSku.specificationsValue != ''">
          <el-input size="small" v-model="editSku.specificationsValue" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="规格名"  v-if="editSku.specificationsValue == ''">
          <el-input size="small" v-model="editSku.specifications" auto-complete="off" placeholder="请输入规格名"></el-input>
        </el-form-item>
         <el-form-item label="规格值"  v-if="editSku.specificationsValue == ''">
          <el-input size="small" v-model="editSku.value" auto-complete="off" placeholder="请输入规格值"></el-input>
        </el-form-item>
        <el-form-item label="规格图"  v-if="editSku.specificationsValue != ''">
          <!-- <el-input size="small" v-model="editSku.picUrl" auto-complete="off" placeholder="请输入规格图"></el-input> -->
          <el-upload
            action="qiniuDomain"
            list-type="picture-card"
            :http-request="upLoadToQiniuSku"
            :show-file-list="false"
            :before-upload="beforeUpload">
             <img v-if="editSku.picUrl" :src="editSku.picUrl" class="avatar">
             <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
           <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
         <el-form-item label="规格价格"  v-if="editSku.specificationsValue != ''">
          <el-input size="small" v-model="editSku.price" auto-complete="off" placeholder="请输入规格价格"></el-input>
        </el-form-item>
        <el-form-item  width="100" align="center">
            <el-button size="mini" type="primary" @click="addSku" v-if="editSku.specificationsValue == ''">添加</el-button>
            <el-button size="mini" type="primary" @click="updateSku" v-if="editSku.specificationsValue != ''">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加商品参数界面 -->
    <!-- <GoodsAttribute
      :editAttributeVisible.sync="editAttributeVisible"
      :editAttribute="editAttribute"
      @addAttribute="addAttribute"
      @closeAttributeDialog="closeAttributeDialog"
    >
    </GoodsAttribute> -->
    <!-- 添加sku界面 -->
    <el-dialog
      title="商品参数"
      :visible.sync="editAttributeVisible"
      width="60%"
      @click="closeAttributeDialog"
    >
      <el-form label-width="90px" ref="editAttribute">
        <el-form-item label="规格名">
          <el-input
            size="small"
            v-model="editAttribute.attribute"
            auto-complete="off"
            placeholder="请输入规格名"
          ></el-input>
        </el-form-item>
        <el-form-item label="规格值">
          <el-input
            size="small"
            v-model="editAttribute.value"
            auto-complete="off"
            placeholder="请输入规格值"
          ></el-input>
        </el-form-item>
        <el-form-item width="100" align="center">
          <el-button size="mini" type="primary" @click="addAttribute"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// import { deptList, deptSave, deptDelete } from '../../api/userMG'
import Pagination from "../../components/Pagination";
import {
  goodsList,
  categoryList,
  addGoods,
  goodsDetail,
  updateGoods,
} from "../../api/goodsMG";
import GoodsSku from "./GoodsSku";
import GoodsAttribute from "./GoodsAttribute";
import { cdn } from "../../../config/qiniuConfig";
import { uploadToken } from "../../api/uploadMG";
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      editSkuVisible: false, //sku编辑框
      editAttributeVisible: false, //商品参数编辑框
      title: "添加",
      dialogVisible: false, //图片上传
      // 实名认证后创建的存储空间对应的上传地址(华东，华南等等不一样：https://developer.qiniu.com/kodo/manual/1671/region-endpoint)
      qiniuDomain: cdn.qiniuDomain,
      // 创建成功后官方随机分配的公开图片地址前缀，即上传成功后对应的公用图片地址前缀
      qiniuViewHost: cdn.host,
      dialogImageUrl: "",
      editForm: {
        id: 0,
        name: "",
        categoryId: "",
        isOnSale: 1,
        sortOrder: 50,
        picUrl: "",
        isShow: 1,
        isHot: 1,
        detail: "",
        price: "",
        // 编辑表所显示的sku记录
        goodsProductVo: [],
        // 单纯规格表
        goodSpecificationsVo: [],
        // 临时规格
        spec: [],
        goodsAttributeVo: [],
      },
      editSku: {
        specifications: "",
        value: "",
        picUrl: "",
        price: "",
        specificationsValue: "",
      },
      editAttribute: {
        attribute: "",
        value: "",
      },
      // rules表单验证
      // rules: {
      //   deptName: [
      //     { required: true, message: '请输入部门名称', trigger: 'blur' }
      //   ],
      //   deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      // },
      formInline: {
        size: 1,
        current: 10,
        // varLable: '',
        // varName: '',
        // token: localStorage.getItem('logintoken')
      },
      searchGoods: {
        goodsName: "",
      },
      // 删除部门
      seletedata: {
        ids: "",
        token: localStorage.getItem("logintoken"),
      },
      userparm: [], //搜索权限
      listData: [], //商品数据
      categoryList: [], //类目列表

      // 分页参数
      pageparm: {
        current: 1,
        size: 10,
        total: 10,
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
    GoodsSku,
    GoodsAttribute,
  },

  /**
   * 创建完毕
   */
  created() {
    this.formInline.current = 1;
    this.formInline.size = 10;
    let data = {
      pageVo: this.formInline,
    };
    this.getdata(data);
    this.getCategoryList();
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取类目列表
    async getCategoryList() {
      let that = this;
      await categoryList().then((res) => {
        if (res.code == "200") {
          that.categoryList = res.data;
        }
      });
    },
    // 获取商品列表
    async getdata(parameter) {
      let that = this;
      await goodsList(parameter).then((res) => {
        if (res.code == "200") {
          that.loading = false;
          that.listData = res.data.records;
          that.pageparm.current = res.data.current;
          that.pageparm.size = res.data.size;
          that.pageparm.total = res.data.total;
        } else {
          that.loading = true;
        }
      });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.current = parm.current;
      this.formInline.size = parm.size;
      let data = {
        pageVo: this.formInline,
      };
      this.getdata(data);
    },
    // 搜索事件
    search() {
      let formData = {
        pageVo: this.formInline,
        goodsName: this.searchGoods.goodsName,
      };
      this.getdata(formData);
    },
    // 显示添加sku
    addSkuDialog() {
      // debugger
      this.editSkuVisible = true;
      this.editSku = {
        specifications: "",
        value: "",
        picUrl: "",
        price: "",
        specificationsValue: "",
      };
    },
    // 添加sku
    addSku(parameter) {
      // console.log(parameter)
      let editForm = this.editForm;
      let editSku = this.editSku;
      if (editForm.goodsProductVo.length == 0) {
        let sku = {
          picUrl: null,
          price: 1,
          number: null,
          specifications: editSku.specifications + ":" + editSku.value,
          productSn: null,
        };
        editForm.goodsProductVo.push(sku);
        let skuSpecifications = {
          specifications: editSku.specifications,
          value: editSku.value,
        };
        editForm.goodSpecificationsVo.push(skuSpecifications);

        editForm.spec.push([editSku.specifications + ":" + editSku.value]);
      } else {
        // 添加的是否重复有，若true，则重复，不添加，若false，则添加
        let flag = true;
        let addIndex = -1;

        // spec处理
        let spec = editForm.spec;
        for (let index in spec) {
          if (spec[index][0].includes(editSku.specifications + ":")) {
            addIndex = index;
            for (let subIndex in spec[index]) {
              if (
                spec[index][subIndex].includes(
                  editSku.specifications + ":" + editSku.value
                )
              ) {
                flag = false;
                break;
              }
            }
          }
        }
        if (!flag) {
          // 重复规格了
          return;
        }
        if (addIndex == -1) {
          // 如果为新属性
          spec.push([editSku.specifications + ":" + editSku.value]);
        } else {
          // 如果存在该属性却不同值
          spec[addIndex].push(editSku.specifications + ":" + editSku.value);
        }
        // 表格进一步修改
        editForm.goodsProductVo = [];
        let skuList = editForm.goodsProductVo;
        let allSpecArray = this.cartesianProductOf(...spec);
        for (let index in allSpecArray) {
          let sku = {
            picUrl: null,
            price: 1,
            number: null,
            specifications: allSpecArray[index].substring(
              0,
              allSpecArray[index].lastIndexOf(",")
            ),
            productSn: null,
          };
          skuList.push(sku);
        }
        // 加单规格
        let skuSpecifications = {
          specifications: editSku.specifications,
          value: editSku.value,
        };
        editForm.goodSpecificationsVo.push(skuSpecifications);
      }

      this.editSku = {
        specifications: "",
        value: "",
        picUrl: "",
        price: "",
        specificationsValue: "",
      };
      this.closeSkuDialog()
    },
    updateSkuDialog(index, row) {
      // console.log(row)
      //console.log(row)//row中就包含了你点击的那一行的数据
      //console.log(row.jur_name);//打印出这一行的jur_name（“honey”）
      this.editSkuVisible = true;
      this.editSku = {
        specifications: "",
        value: "",
        picUrl: row.picUrl,
        price: row.price,
        specificationsValue: row.specifications,
        index,
      };
    },
    // 修改sku
    updateSku() {
      let index = this.editSku.index;
      let skuList = this.editForm.goodsProductVo;
      skuList[index].picUrl = this.editSku.picUrl;
      skuList[index].price = this.editSku.price;

      this.editSku = {
        specifications: "",
        value: "",
        picUrl: "",
        price: "",
        specificationsValue: "",
      };
      this.closeSkuDialog()
    },
    // 删除sku
    deleteSku(index, row) {
      this.editForm.goodsProductVo.splice(index, 1);
    },
    // 显示添加商品参数界面
    addAttributeDialog() {
      this.editAttributeVisible = true;
      this.editAttribute = {
        attribute: "",
        value: "",
      };
    },
    // 添加商品参数
    addAttribute() {
      let goodsAttributeList = this.editForm.goodsAttributeVo;
      goodsAttributeList.push(this.editAttribute);
      this.closeAttributeDialog()
    },
    cartesianProductOf() {
      return Array.prototype.reduce.call(
        arguments,
        function (a, b) {
          var ret = [];
          a.forEach(function (a) {
            b.forEach(function (b) {
              ret.push(a.concat([b]) + ",");
            });
          });
          return ret;
        },
        [[]]
      );
    },
    // 删除商品参数
    deleteAttribute(index, row) {
      this.editForm.goodsAttributeVo.splice(index, 1);
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改商品";
        let that = this;

        goodsDetail(row.id).then((res) => {
          if (res.code == "200") {
            let data = res.data;
            let goodsSpecificationsEntities = data.goodsSpecificationsEntities;
            // spec处理
            let spec = [];
            for (let specIndex in goodsSpecificationsEntities) {
              if (spec == []) {
                spec.push([
                  goodsSpecificationsEntities[specIndex].specifications +
                    ":" +
                    goodsSpecificationsEntities[specIndex].value,
                ]);
                continue;
              }
              let flag = true;
              let addIndex = -1;
              for (let index in spec) {
                if (
                  spec[index][0].includes(
                    goodsSpecificationsEntities[specIndex].specifications + ":"
                  )
                ) {
                  addIndex = index;
                  for (let subIndex in spec[index]) {
                    if (
                      spec[index][subIndex].includes(
                        goodsSpecificationsEntities[specIndex].specifications +
                          ":" +
                          goodsSpecificationsEntities[specIndex].value
                      )
                    ) {
                      flag = false;
                      break;
                    }
                  }
                }
              }
              if (!flag) {
                // 重复规格了
                continue;
              } else if (addIndex == -1) {
                // 如果为新属性
                spec.push([
                  goodsSpecificationsEntities[specIndex].specifications +
                    ":" +
                    goodsSpecificationsEntities[specIndex].value,
                ]);
              } else {
                // 如果存在该属性却不同值
                spec[addIndex].push(
                  goodsSpecificationsEntities[specIndex].specifications +
                    ":" +
                    goodsSpecificationsEntities[specIndex].value
                );
              }
            }

            this.editForm = {
              id: data.goods.id,
              name: data.goods.name,
              categoryId: data.goods.categoryId,
              isOnSale: data.goods.isOnSale,
              sortOrder: data.goods.sortOrder,
              picUrl: data.goods.picUrl,
              isShow: data.goods.isShow,
              isHot: data.goods.isHot,
              detail: data.goods.detail,
              price: data.goods.price,
              // 编辑表所显示的sku记录
              goodsProductVo: data.goodsProductEntities,
              // 单纯规格表
              goodSpecificationsVo: goodsSpecificationsEntities,
              // 临时规格
              spec,
              goodsAttributeVo: data.goodsAttributeEntities,
            };
          }
        });
      } else {
        this.title = "添加商品";
        this.editForm = {
          id: 0,
          name: "",
          categoryId: "",
          isOnSale: 1,
          sortOrder: 50,
          picUrl: "",
          isShow: 1,
          isHot: 1,
          detail: "",
          price: "",
          // 编辑表所显示的sku记录
          goodsProductVo: [],
          // 单纯规格表
          goodSpecificationsVo: [],
          // 临时规格
          spec: [],
          goodsAttributeVo: [],
        };
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
      if (this.editForm.id == 0) {
        addGoods(this.editForm)
          .then((res) => {
            this.editFormVisible = false;
            this.loading = false;
            if (res.code == 200) {
              let data = {
                pageVo: this.formInline,
              };
              this.getdata(data);
              this.$message({
                type: "success",
                message: "商品添加成功！",
              });
            } else {
              this.$message({
                type: "info",
                message: res.msg,
              });
            }
          })
          .catch((err) => {
            this.editFormVisible = false;
            this.loading = false;
            this.$message.error("商品添加失败，请稍后再试！");
          });
      } else {
        updateGoods(this.editForm)
          .then((res) => {
            this.editFormVisible = false;
            this.loading = false;
            if (res.code == 200) {
              let data = {
                pageVo: this.formInline,
              };
              this.getdata(data);
              this.$message({
                type: "success",
                message: "商品修改成功！",
              });
            } else {
              this.$message({
                type: "info",
                message: res.msg,
              });
            }
          })
          .catch((err) => {
            this.editFormVisible = false;
            this.loading = false;
            this.$message.error("商品修改失败，请稍后再试！");
          });
      }
    },

    // 图片上传(商品主图)
    async upLoadToQiniu(req) {
      const config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      let fileType = "";
      if (req.file.type === "image/png") {
        fileType = "png";
      } else {
        fileType = "jpg";
      }
      // 重命名要上传的文件
      const keyname = `${new Date().getTime()}${Math.random()
        .toString(36)
        .slice(2)}.${fileType}`;
      // 上传时候的Token,可前端自己生成,安全起见后端生成！
      // 获取Token
      let token = "";
      await uploadToken().then((res) => {
        if (res.code == "200") {
          token = res.data;
        } else {
          // that.loading = true
        }
      });
      const formdata = new FormData();
      formdata.append("file", req.file);
      formdata.append("token", token);
      formdata.append("key", keyname);

      const result = await this.$http.post(this.qiniuDomain, formdata, config);

      // http://qp0e5erxn.hn-bkt.clouddn.com/1614150299156jajg0szk7rs.png
      this.editForm.picUrl = cdn.realHost + "/" + keyname;
    },

    // 上传图片（sku）
    async upLoadToQiniuSku(req) {
      const config = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      let fileType = "";
      if (req.file.type === "image/png") {
        fileType = "png";
      } else {
        fileType = "jpg";
      }
      // 重命名要上传的文件
      const keyname = `${new Date().getTime()}${Math.random().toString(36).slice(2)}.${fileType}`;
      // 上传时候的Token,可前端自己生成,安全起见后端生成！
      // 获取Token
      let token = '';
      await uploadToken().then(res => {
        if(res.code == '200') {
          token = res.data
        } else {
          // that.loading = true
        }
      })
      const formdata = new FormData();
      formdata.append("file", req.file);
      formdata.append("token", token);
      formdata.append("key", keyname);

      const result = await this.$http.post(this.qiniuDomain, formdata, config);

      // http://qp0e5erxn.hn-bkt.clouddn.com/1614150299156jajg0szk7rs.png
      this.editSku.picUrl = cdn.realHost + "/" + keyname
    },

    // 上传图片前的校验
    beforeUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message({
          showClose: true,
          message: "上传图片只能是JPG/PNG 格式!",
          type: "error",
        });
      }
      if (!isLt5M) {
        this.$message({
          showClose: true,
          message: "上传头像图片大小不能超过 5MB!",
          type: "error",
        });
      }
      return isJPG && isLt5M;
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },
    closeSkuDialog() {
      this.editSkuVisible = false;
    },
    closeAttributeDialog() {
      this.editAttributeVisible = false;
    }
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>

 
 